<?php

namespace falcon5\inc\Http\Controllers;

use falcon5\inc\Base\Common;
use falcon5\inc\Base\ProxyHeader;
use falcon5\inc\Base\WPOption;
use falcon5\inc\Helpers\UrlHelper;
use falcon5\inc\Infrastructure\Clients\FC5Client;
use falcon5\inc\Infrastructure\Services\CacheService;
use falcon5\inc\Infrastructure\Services\Falcon5Service;
use hollisho\helpers\ArrayHelper;
use hollisho\helpers\InvalidArgumentException;
use hollisho\httpclient\Feign\FeignClientFactory;
use falcon5\inc\Http\JsonResponse;
use falcon5\inc\Http\Request;
use lucatume\DI52\ContainerException;

class SettingsController extends BaseController
{

    /**
     * save settings
     * @param Request $request
     * @return JsonResponse
     * @throws InvalidArgumentException
     * @throws ContainerException
     */
    public function saveSettings(Request $request): JsonResponse
    {
        // 检查用户权限
        if (!current_user_can('manage_options')) {
            return JsonResponse::error(403, 'Insufficient permissions');
        }

        // 获取传递的数据
        $settings = $request->get('settings');

        if (!$settings) {
            return JsonResponse::error(400, 'Invalid setting');
        }

        $settings = stripslashes($settings);
        $settings = json_decode($settings, true);
        $targeLanges = "";
        if(!empty($settings['selectedLanguages'])){
            foreach ($settings['selectedLanguages'] as $key => $value) {
                if($key > 0){
                    $targeLanges .= ",";
                }
                $targeLanges .= $value["code"];
            }
        }
       
        if (!isset($settings['activityTicket'])) {
            return JsonResponse::error(400, 'falcon5 api key is require');
        }

        $settings['selectedLanguages'][] = [
            'code' => $settings['originalLanguage'],
            'name' => ArrayHelper::getValue(falcon5_support_languages(), $settings['originalLanguage'])
        ];

        // 获取当前设置
        $current_settings = get_option(Common::PLUGIN_ID, []);

        // 判断 activityTicket 是否有改变
        if (!isset($current_settings['activityTicket']) || $current_settings['activityTicket'] !== $settings['activityTicket']) {
            /** @var CacheService $cacheService */
            $cacheService = falcon5_app(CacheService::class);
            $cacheService->delAllCache();
        }

        try {
            $client = FeignClientFactory::create(FC5Client::class, [
                'headers' => [
                    ProxyHeader::FC5_API_KEY => $settings['activityTicket']
                ],
                'base_uri' => Common::getPlatformProxyHost()
            ]);
            
            /** @var Falcon5Service $service */
            $service = falcon5_app(Falcon5Service::class);
            $service->setClient($client);
           
            $result = $service->updateSite([
                'domain' => UrlHelper::getHost(),
                'api_key' => $settings['activityTicket'],
                'original_language' => ArrayHelper::getValue($settings, 'originalLanguage'),
                'target_language' => $targeLanges
            ]);
            
            if (ArrayHelper::getValue($result, 'code') != 1) {
                $error = sprintf("%s:%s", ArrayHelper::getValue($result, 'msg'), ArrayHelper::getValue($result, 'code'));
                throw new \Exception($error);
            }
            
        } catch (\Exception $e) {
            return JsonResponse::error(500, $e->getMessage());
        }

        update_option(Common::PLUGIN_ID, $settings);
        return JsonResponse::success([
            'message' => 'success'
        ]);
    }

    /**
     * fetch settings
     * @param Request $request
     * @return JsonResponse
     * @throws InvalidArgumentException
     */
    public function getSettings(Request $request): JsonResponse
    {
        /** @var  $settings */
        $settings = get_option(Common::PLUGIN_ID, []);

        if (!$settings) {
            $settings['selectedLanguages'] = [
                ['code' => 'en', 'name' => 'English'],
                ['code' => 'zh-cn', 'name' => 'Chinese(Simplified)'],
            ];

            $settings['buttonDesign'] = [
                'floatingSelector' => 'top-right'
            ];
        }

        $settings['homeUrl'] = home_url();
        $get_protocol_and_domain = get_protocol_and_domain($settings['homeUrl']);
        $settings['protocol'] = ArrayHelper::getValue($get_protocol_and_domain, 'protocol');
        $settings['domain'] = ArrayHelper::getValue($get_protocol_and_domain, 'domain');
        return JsonResponse::success($settings);
    }

    /**
     * fetch cache directory
     * @param Request $request
     * @return JsonResponse
     */
    public function getCacheDirectory(Request $request): JsonResponse
    {
        $falcon5_cache_dir = falcon5_cache_dir();
        $writable = falcon5_cache_dir_is_writable();
        $relative_path = str_replace(ABSPATH, '', $falcon5_cache_dir);
        return JsonResponse::success([
            'path' => strlen($relative_path)>4?$relative_path:$falcon5_cache_dir,
            'writable' => $writable
        ]);
    }

    /**
     * validate domain
     * @param Request $request
     * @return JsonResponse
     */
    public function validateDomain(Request $request): JsonResponse
    {
        // 检查用户权限
        if (!current_user_can('manage_options')) {
            return JsonResponse::error(403, 'Insufficient permissions');
        }

        // 获取传递的参数
        $subdomain = $request->get('sub_domain');
        $langCode = $request->get('lang_code');

        if (empty($subdomain) || empty($langCode)) {
            return JsonResponse::error(400, 'Missing required parameters');
        }

        try {
            /** @var WPOption $falcon5Option */
            $falcon5Option = falcon5_app(WPOption::class);
            $originalLanguage = $falcon5Option->getOriginalLanguage();

            if ($langCode == $originalLanguage) {
                return JsonResponse::success([
                    'isValid' => true
                ]);
            }

            $home_url = home_url();
            $get_protocol_and_domain = get_protocol_and_domain($home_url);
            $protocol = ArrayHelper::getValue($get_protocol_and_domain, 'protocol');
            $domain = ArrayHelper::getValue($get_protocol_and_domain, 'domain');

            // 构建完整的子域名和URL
            $finalDomain = sprintf("%s.%s", $langCode, $domain);
            $url = sprintf("%s://%s", $protocol, $finalDomain);

            // 检查域名是否可用
//            if (!check_domain_availability($finalDomain)) {
//                wp_send_json_success([
//                    'isValid' => false,
//                    'message' => 'Domain is not available'
//                ]);
//                wp_die();
//            }

            // 检查HTTP访问和服务标识
            $http_check = check_domain_http($url, get_authorization());
            if (!$http_check['status']) {
                return JsonResponse::success([
                    'isValid' => false,
                    'message' => 'Domain is not accessible :' . json_encode($http_check)
                ]);
            }

            // 所有检查都通过
            return JsonResponse::success([
                'isValid' => true
            ]);
        } catch (\Exception $e) {
            return JsonResponse::error(500, $e->getMessage());
        }
    }
}